package com.starhub.application.agent.concurrent;

import org.springframework.stereotype.Component;

import com.starhub.application.agent.config.ConcurrencyConfig;

import java.util.concurrent.Callable;

/*** */
@Component
public class ConcurrentTaskExecutor {
    private final ConcurrencyConfig config;
    private final ConcurrencyCounter counter;

    public ConcurrentTaskExecutor(ConcurrencyConfig config, ConcurrencyCounter counter) {
        this.config = config;
        this.counter = counter;
    }

    /**
     * 执行任务前检查并发限制
     */
    private void checkConcurrencyLimit(Long agentId) {
        int agentCount = counter.getAgentCount(agentId);
        int totalCount = counter.getTotalCount();

        if (agentCount >= config.getPerAgentLimit()) {
            throw new RuntimeException("智能体并发数超过限制: " + agentId);
        }
        if (totalCount >= config.getTotalLimit()) {
            throw new RuntimeException("总体并发数超过限制");
        }
    }

    /**
     * 执行任务
     */
    public <T> T execute(Long agentId, Callable<T> task) throws Exception {
        try {
            // 检查并发限制
            checkConcurrencyLimit(agentId);
            
            // 增加计数器
            counter.incrementAgentCount(agentId);
            counter.incrementTotalCount();
            
            // 执行任务
            return task.call();
        } finally {
            // 减少计数器
            counter.decrementAgentCount(agentId);
            counter.decrementTotalCount();
        }
    }
} 